using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

using IdentityModel;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NP.BPMReportPlatform.EntityFrameworkCore;

using StackExchange.Redis;
using Microsoft.OpenApi.Models;

using Newtonsoft.Json.Serialization;

using NP.BPMReportPlatform.Filters;
using NP.BPMReportPlatform.JsonConverters;

using Serilog;
using Serilog.Events;

using Volo.Abp;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Autofac;
using Volo.Abp.Caching;
using Volo.Abp.Caching.StackExchangeRedis;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.MySQL;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.Security.Claims;
using Volo.Abp.Swashbuckle;
using Volo.Abp.VirtualFileSystem;
using NP.Enterprise.Utils.Http;
using zipkin4net.Transport.Http;
using zipkin4net.Middleware;
using zipkin4net.Tracers.Zipkin;
using zipkin4net;
using NP.Enterprise.Utils.Extension;
using NP.BPMReportPlatform.AuthorizationUserManager.Dtos;

namespace NP.BPMReportPlatform
{
    [DependsOn(
        typeof(BPMReportPlatformApplicationModule),
        typeof(BPMReportPlatformEntityFrameworkCoreModule),
        typeof(BPMReportPlatformHttpApiModule),
        typeof(AbpAutofacModule),
        typeof(AbpCachingStackExchangeRedisModule),
        typeof(AbpEntityFrameworkCoreMySQLModule),
        // typeof(AbpAuditLoggingEntityFrameworkCoreModule),
        // typeof(AbpPermissionManagementEntityFrameworkCoreModule),
        // typeof(AbpSettingManagementEntityFrameworkCoreModule),
        typeof(AbpAspNetCoreSerilogModule),
        typeof(AbpSwashbuckleModule)
        )]
    public class BPMReportPlatformHttpApiHostModule : AbpModule
    {

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration = context.Services.GetConfiguration();

            // Log.Logger = new LoggerConfiguration()
            //    .MinimumLevel.Debug()
            //    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            //    .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            //    .Enrich.WithProperty("Application", "NP.BPMReportPlatform.HttpApi.Host")
            //    .Enrich.FromLogContext()
            //    .ReadFrom.Configuration(configuration)
            //    .CreateLogger();

            // 使用serilog作为log发送方
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                .Enrich.WithProperty("Application", "NP.BPMReportPlatform.HttpApi.Host")
                .Enrich.FromLogContext()
                .ReadFrom.Configuration(configuration)
                .WriteTo.Console()
                .CreateLogger();

            context.Services.AddLogging(loggingBuilder =>
                loggingBuilder.AddSerilog(dispose: true));

             context.Services.AddSingleton(typeof(Serilog.ILogger), Log.Logger);

            Configure<AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
            });

            if (hostingEnvironment.IsEnvironment("Local"))
            {
                Configure<AbpVirtualFileSystemOptions>(options =>
                {
                    options.FileSets.ReplaceEmbeddedByPhysical<BPMReportPlatformDomainSharedModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}NP.BPMReportPlatform.Domain.Shared", Path.DirectorySeparatorChar)));
                    options.FileSets.ReplaceEmbeddedByPhysical<BPMReportPlatformDomainModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}NP.BPMReportPlatform.Domain", Path.DirectorySeparatorChar)));
                    options.FileSets.ReplaceEmbeddedByPhysical<BPMReportPlatformApplicationContractsModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}NP.BPMReportPlatform.Application.Contracts", Path.DirectorySeparatorChar)));
                    options.FileSets.ReplaceEmbeddedByPhysical<BPMReportPlatformApplicationModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}NP.BPMReportPlatform.Application", Path.DirectorySeparatorChar)));
                });
            }

            ConfigureSwagger(context, configuration);
            CapConfigureServices(context.Services, configuration);

            context.Services.AddSingleton<INPRestHttpHelper, NPRestHttpHelper>();

            Configure<AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
                options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish"));
                options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
                options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi", "in"));
                options.Languages.Add(new LanguageInfo("it", "it", "Italian", "it"));
                options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
                options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
                options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
                options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak"));
                options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
                options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
            });

            Configure<AbpDistributedCacheOptions>(options =>
            {
                options.KeyPrefix = "BPMReportPlatform:";
            });

            if (!hostingEnvironment.IsEnvironment("Local"))
            {
                var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
                context.Services
                    .AddDataProtection()
                    .PersistKeysToStackExchangeRedis(redis, "BPMReportPlatform-Protection-Keys");
            }

            ConfigureRedis(context, configuration);

            //Updates AbpClaimTypes to be compatible with identity server claims.
            AbpClaimTypes.UserId = JwtClaimTypes.Subject;
            AbpClaimTypes.UserName = JwtClaimTypes.Name;
            AbpClaimTypes.Role = JwtClaimTypes.Role;
            AbpClaimTypes.Email = JwtClaimTypes.Email;

            context.Services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = false;
                    options.ApiName = configuration["AuthServer:ApiName"];
                });

            context.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder
                        .WithOrigins(
                            configuration["App:CorsOrigins"]
                                .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                .Select(o => o.RemovePostFix("/"))
                                .ToArray()
                        )
                        .WithAbpExposedHeaders()
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });

            context.Services.AddCustomWrapping();

            context.Services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Latest).AddJsonOptions(option =>
                {
                    //原样输出,默认会把首字母小写
                    option.JsonSerializerOptions.PropertyNamingPolicy = null;
                    option.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter());
                })
                // .AddNewtonsoftJson(options =>
                //     options.SerializerSettings.ContractResolver = new DefaultContractResolver())
                .AddCustomMvcApiResult();

            Volo.Abp.Application.Dtos.LimitedResultRequestDto.MaxMaxResultCount = int.MaxValue;

            //context.Services.AddJaeger();
            //context.Services.AddOpenTracing(builder =>
            //{
            //    builder.ConfigureAspNetCore(options =>
            //    {
            //        options.Hosting.IgnorePatterns.Add(ctx => ctx.Request.Path == "/health");
            //    });
            //});

            context.Services.AddHealthChecks(); // 添加健康检查服务

            //var armsAppName = configuration["Arms:ApplicationName"];

            //context.Services.AddHttpClient("Tracer").AddHttpMessageHandler(provider => TracingHandler.WithoutInnerHandler(armsAppName));

        }

        private static void ConfigureSwagger(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddSwaggerGen(
                options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo { Title = "BPM报表 API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
                    options.CustomSchemaIds(type => type.FullName);
                    options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                    options.IncludeXmlComments(ControllerXmlCommentsFilePath);
                    options.IncludeXmlComments(DtoXmlCommentsFilePath);
                    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                    {
                        Description = "Swagger使用JWT来进行授权 在下方输入Bearer {token} 即可，注意两者之间有空格",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey,
                        Scheme = "Bearer"
                    });
                    options.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                            },
                            new string[] {}
                        }
                    });
                });
        }

        private static string ControllerXmlCommentsFilePath
        {
            get
            {
                var basePath = AppContext.BaseDirectory;
                var fileName = typeof(BPMReportPlatformHttpApiModule).GetTypeInfo().Assembly.GetName().Name + ".xml";
                return Path.Combine(basePath, fileName);
            }
        }

        private static string DtoXmlCommentsFilePath
        {
            get
            {
                var basePath = AppContext.BaseDirectory;
                var fileName = typeof(BPMReportPlatformApplicationContractsModule).GetTypeInfo().Assembly.GetName().Name + ".xml";
                return Path.Combine(basePath, fileName);
            }
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();
            var _configuration = context.GetConfiguration();

            if (env.IsEnvironment("Local"))
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // app.UseErrorPage();
                // app.UseHsts();
            }

            // app.UseHttpsRedirection();
            app.UseCorrelationId();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors();
            app.UseAuthentication();
            app.UseAbpClaimsMap();
            app.UseAbpRequestLocalization();
            app.UseAuthorization();

            app.UseSwaggerBasicAuth(new Enterprise.Utils.Extension.Dtos.SwaggerBasicAuthDto()
            {
                UserName = _configuration["Swagger:UserName"],
                Password = _configuration["Swagger:Password"],
                SwaggerEndpoint = _configuration["Swagger:SwaggerEndpoint"],
            });
            app.UseSwagger();
            app.UseAbpSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Support APP API");
            });
            // app.UseAuditing();
            app.UseAbpSerilogEnrichers();
            app.UseConfiguredEndpoints();

            app.UseHealthChecks("/health"); // 配置健康检查中间件

            //var loggerFactory = app.ApplicationServices.GetService<Microsoft.Extensions.Logging.ILoggerFactory>();
            //var configuration = context.GetConfiguration();

            //var armsAppName = configuration["Arms:ApplicationName"];

            //var lifetime = app.ApplicationServices.GetService<IHostApplicationLifetime>();
            //lifetime.ApplicationStarted.Register(() =>
            //{
            //    TraceManager.SamplingRate = 1.0f;
            //    var logger = new TracingLogger(loggerFactory, "zipkin4net");
            //    var httpSender = new HttpZipkinSender(configuration["Arms:Url"], "application/json");
            //    var tracer = new ZipkinTracer(httpSender, new JSONSpanSerializer());
            //    TraceManager.RegisterTracer(tracer);
            //    TraceManager.Start(logger);
            //});
            //lifetime.ApplicationStopped.Register(() => TraceManager.Stop());
            //app.UseTracing(armsAppName);

        }

        public void CapConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddCap(x =>
            {
                x.UseMySql(configuration["ConnectionStrings:BPM_Business"]);

                x.UseRabbitMQ(option =>
                {
                    option.VirtualHost = configuration["RabbitMQ:Connections:Default:VirtualHost"];     //虚拟通道
                    option.HostName = configuration["RabbitMQ:Connections:Default:HostName"];           //IP地址
                    option.UserName = configuration["RabbitMQ:Connections:Default:UserName"];           //账号
                    option.Password = configuration["RabbitMQ:Connections:Default:Password"];           //密码 
                    option.Port = Convert.ToInt32(configuration["RabbitMQ:Connections:Default:Port"]);  //端口号
                });

                x.FailedRetryCount = 2;
                x.FailedRetryInterval = 5 * 60;
                x.FailedThresholdCallback = (type) =>
                {
                    Log.Logger.Error($"Cap异常：{type.Message}");
                };
            });
        }

        private void ConfigureRedis(ServiceConfigurationContext context, IConfiguration configuration)
        {
            //平台用户授权数据缓存库
            context.Services.AddEasyCaching(options =>
            {
                options.UseRedis(config =>
                {
                    config.DBConfig.Configuration = configuration["Redis:PermissionsConfiguration"];
                }, PermissionCacheConsts.CacheProviderKey)
                    .WithMessagePack();
            });
        }
    }
}
